package com.handu.luna.boss.controller.support;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.handu.luna.core.domain.admin.AdminControllerDescription;

@ControllerAdvice
public class GlobalExceptionHandler {
	private Log logger = LogFactory.getLog(this.getClass());
	
	//private String ajaxErrorView;
	private String ajaxDefaultErrorMessage = "发生了问题：";
	private boolean ajaxShowTechMessage = true;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ExceptionHandler()
	public @ResponseBody Object resolveException(HttpServletRequest request,
			HttpServletResponse response, Object o, Exception e) {
		logger.debug("global error",e);
		
		if (isAjax(request)) {
			String exceptionMessage = ajaxDefaultErrorMessage;
			if (ajaxShowTechMessage)
				exceptionMessage += "\n" + getExceptionMessage(e);
//			ModelAndView m = new ModelAndView(ajaxErrorView);
//			m.addObject("exceptionMessage", exceptionMessage);
			Map model = new HashMap();
			model.put("errors", exceptionMessage);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return model;
		} else {
			ModelAndView errorPage = new ModelAndView("error/error");
			errorPage.addObject("exception", e.getMessage());
			//errorPage.addObject("exceptionStack", e.printStackTrace(arg0););
			errorPage.addObject("controllerDescription", AdminControllerDescription.createErrorDescription());
			return errorPage;
		}
	}

	private String getExceptionMessage(Throwable e) {
		String message = "";
		while (e != null) {
			message += e.getMessage() + "\n";
			e = e.getCause();
		}
		return message;
	}

	private boolean isAjax(HttpServletRequest request) {
		return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
	}
}
